package com.kzd.gtboon.app

import android.content.Context
import android.content.pm.PackageManager
import androidx.multidex.MultiDex
import com.blankj.utilcode.util.AppUtils
import com.kzd.gtboon.R
import com.kzd.gtboon.app.SPSConstance.channel
import com.kzd.gtboon.app.SPSConstance.forceLogin
import com.kzd.gtboon.utils.ApkFile
import com.module.lemlin.http.HttpServiceFactory
import com.module.lemlin.app.OwnerApplication
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import org.json.JSONObject
import rxhttp.RxHttpPlugins

class GTApplication : OwnerApplication() {

    companion object {
        init {
            //设置全局的Header构建器
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
                MaterialHeader(context).setColorSchemeResources(R.color.colorMain)
            }
            //设置全局的Footer构建器
            SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
                ClassicsFooter(context)//.setSpinnerStyle(SpinnerStyle.Translate).setAccentColorId(R.color.colorPrimary)
            }
        }
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        //初始dex
        MultiDex.install(base)
    }

    override fun onCreate() {
        super.onCreate()

        if (SPSConstance.isReadAgree == true) {
            initSDK()
        }
    }

    fun initSDK(): Boolean {

        val meatInfo = ApkFile.readMETAINFO(this, "META-INF/gtboon.channel.properties")
        if (meatInfo.isNullOrEmpty()) {
            val appInfo = packageManager.getApplicationInfo(
                packageName, PackageManager.GET_META_DATA
            )
            channel = appInfo.metaData
                .getString("UMENG_CHANNEL", "DEFAULT")
            forceLogin = appInfo.metaData
                .getBoolean("FORCE_LOGIN", false)
        } else {
            channel = try {
                JSONObject(meatInfo).getString("UMENG_CHANNEL")
            } catch (e: Exception) {
                "DEFAULT"
            }
            forceLogin = try {
                JSONObject(meatInfo).getBoolean("FORCE_LOGIN")
            } catch (e: Exception) {
                false
            }
        }

        //初始化RxHttp
        RxHttpPlugins.init(HttpServiceFactory.client().build())
            .setOnParamAssembly {
                it.addHeader("version", AppUtils.getAppVersionName())
                it.addHeader("channel", channel)
                it.addHeader("ua", System.getProperty("http.agent")?.run {
                    substring(indexOf("("), indexOf(")") + 1)
                })
                it.add("uid", SPSConstance.uid)
                it.add("member_id", SPSConstance.memberId)
            }
            .setDebug(true)

        return true
    }

}